package com.powernode.listener;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.constant.QueueConstants;
import com.powernode.domain.Order;
import com.powernode.model.ChangeStock;
import com.powernode.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @create: 2024/7/26
 * @author: gyhe10
 * @description: 订单死信队列监听器
 **/

@Component
@Slf4j
public class OrderDeadListener {

    @Resource
    private OrderService orderService;

    @RabbitListener(queues = QueueConstants.ORDER_DEAD_QUEUE)
    public void handleOrderDeadQueueMsg(Message message, Channel channel) {
        // 获取监听到的消息
        JSONObject jsonObject = JSONObject.parseObject(new String(message.getBody()));
        // 获取订单编号
        String orderNumber = jsonObject.getObject("orderNumber", String.class);
        // 获取商品prod和sku购买数量对象
        ChangeStock changeStock = jsonObject.getObject("changeStock", ChangeStock.class);

        // 根据订单编号查询订单
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNumber, orderNumber));

        // 判断订单是否存在
        if (ObjectUtil.isNull(order)) {
            log.error("订单不存在，订单编号：{}", orderNumber);
            // 签收消息
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }

        // 判断当前订单是否已支付
        if (1 == order.getIsPayed()) {
            // 订单已支付，签收消息
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }

        // 到这里不能确认当前订单是否已支付，需要调用第三方支付机构提供的接口查询订单支付状态
        // 如果查询得到的结果是已支付，则修改订单状态为已支付，并签收消息
        // 如果查询得到的结果是未支付，则修改订单状态为已取消，订单数据回滚
        Boolean isUnPayed = true;
        if (isUnPayed) {
            // 订单数据回滚
            orderService.orderRollback(order, changeStock);
            // 签收消息
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
